package yja.gzw.app.activity

import android.Manifest
import android.app.AlertDialog
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.CountDownTimer
import android.provider.Settings
import android.util.DisplayMetrics
import android.util.Log
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import yja.gzw.app.R
import yja.gzw.app.base.BaseActivity
import yja.gzw.app.databinding.ActivityMainBinding
import yja.gzw.app.model.UserData
import yja.gzw.app.viewmodel.Mainviewmodel

class MainActivity : BaseActivity<Mainviewmodel,ActivityMainBinding>(R.layout.activity_main){
    var isPermissions=false
    var sp: SharedPreferences?=null

    fun isAndroid13(): Boolean {
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU
    }

    override fun initView() {
        sp = this.getSharedPreferences("Shujuku", Context.MODE_PRIVATE)
        if (isAndroid13()) {

            Toast.makeText(this, "当前系统是大于安卓 13 版本api${Build.VERSION.SDK_INT}", Toast.LENGTH_SHORT).show()
            checkAndRequestAndroid13Permissions()
        } else {
            Toast.makeText(this, "当前系统是低于安卓 13 版本api${Build.VERSION.SDK_INT}", Toast.LENGTH_SHORT).show()
            checkAndRequestOldPermissions()
        }
        sp = this.getSharedPreferences("Shujuku", Context.MODE_PRIVATE)


        val metrics = DisplayMetrics()
        windowManager.defaultDisplay.getMetrics(metrics)
        val mWidth = metrics.widthPixels
        val mHeight = metrics.heightPixels

        UserData.kuan=mWidth
        UserData.gao=mHeight








    }

    private fun checkAndRequestAndroid13Permissions() {
        val permissionsToRequest = arrayOf(
            Manifest.permission.READ_MEDIA_IMAGES,
            Manifest.permission.READ_MEDIA_AUDIO,
            Manifest.permission.READ_MEDIA_VIDEO
        )

        val allPermissionsGranted = permissionsToRequest.all {
            ContextCompat.checkSelfPermission(this, it) == PackageManager.PERMISSION_GRANTED
        }

        if (!allPermissionsGranted) {
            ActivityCompat.requestPermissions(this, permissionsToRequest, 101)
        } else {
            proceedAfterPermissionsGranted()
        }
    }


    private fun checkAndRequestOldPermissions() {
        val permissionsToRequest = arrayOf(
            Manifest.permission.READ_EXTERNAL_STORAGE
        )

        val allPermissionsGranted = permissionsToRequest.all {
            ContextCompat.checkSelfPermission(this, it) == PackageManager.PERMISSION_GRANTED
        }

        if (!allPermissionsGranted) {
            ActivityCompat.requestPermissions(this, permissionsToRequest, 101)
        } else {
            proceedAfterPermissionsGranted()
        }
    }


    private fun proceedAfterPermissionsGranted() {


        val countdownTimer = object : CountDownTimer(2000, 1000) {
            override fun onTick(millisUntilFinished: Long) {

            }

            override fun onFinish() {
                val isi= sp?.getBoolean("islogin",false)
                UserData.token=  sp?.getString("token", "")
                UserData.id=  sp?.getString("id", "")
                Log.e("读取用户id1", UserData.id)

                if(isi==true){
                    val intent = Intent(this@MainActivity,TopshowActivity::class.java)
                    finish()
                    startActivity(intent)  // 启动 SecondActivity
                }else{


                    val intent = Intent(this@MainActivity,LogActivity::class.java)
                    finish()
                    startActivity(intent)  // 启动 SecondActivity

                }







            }
        }

        countdownTimer.start()


    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == 101) {
            if (grantResults.isNotEmpty() && grantResults.all { it == PackageManager.PERMISSION_GRANTED }) {
                proceedAfterPermissionsGranted()
            } else {
                showPermissionDeniedDialog()
            }
        }
    }


    private fun showPermissionDeniedDialog() {
        // 显示对话框提示用户权限的重要性，并提供前往设置页面的选项
        val dialog=  AlertDialog.Builder(this)
            .setTitle("权限被拒绝")
            .setMessage("此权限对于应用的正常运行非常重要，请前往设置页面开启权限。")
            .setPositiveButton("前往设置") { _, _ ->
                val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
                val uri = Uri.fromParts("package", packageName, null)
                intent.data = uri
                startActivity(intent)
                isPermissions=true

            }
            .setNegativeButton("取消"){
                    dialog, _ ->
                Toast.makeText(this,"权限被拒绝，无法正常使用应用。", Toast.LENGTH_SHORT).show()

                finishAffinity()

            }
            //.show()

            .create()

        // 设置对话框消失监听器
        dialog.setOnDismissListener {
            // 对话框消失后的操作
            onDialogDismissed()
        }

        // 显示对话框
        dialog.show()

    }

    private fun onDialogDismissed() {
        if(!isPermissions){
            Toast.makeText(this,"权限被拒绝，无法正常使用应用。", Toast.LENGTH_SHORT).show()

            finishAffinity()

        }

    }



    override fun dataObservese() {

    }

}